//
//  HJConversationController.m
//  KaiChat
//
//  Created by lx on 2023/10/16.
//

#import "HJConversationController.h"
#import "QMUIButton.h"
#import "HJPersonalCenterController.h"
#import "HJMinePresent.h"
#import "HJVersionUpdate.h"
#import "HJWebSocketManager.h"
#import "HJIM.h"
#import "HJConversationCell.h"
#import "HJChatController.h"
#import "HJAlertController.h"
#import "HJPopMenuController.h"
#import "QMUITextField.h"
#import "HJAddFriendController.h"
#import "HJNavigationController.h"
#import "HJSelectFridendsController.h"

@interface HJConversationController ()<QMUITextFieldDelegate, HJConversationCellDelegate>

@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, strong) NSArray *originalDatas;
@property (nonatomic, assign) NSInteger systemMessagesCount;
@property (nonatomic, copy) NSString *keyword;
@property (nonatomic, weak) HJPopMenuController *popMenuController;


@end

@implementation HJConversationController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.datas = [NSMutableArray array];
    
    UIImageView *avatarImageView = [UIImageView addToView:self.navigationBar.contentView];
    [avatarImageView tj_setImageWithURL:HJUserInfo.avatar.URL placeholderImage:[UIImage imageNamed:@"avatar"]];
    avatarImageView.addCornerRadius(15);
    [avatarImageView addTapGesturesWithTarget:self action:@selector(tapAvatarImageView)];
    [avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(leftRightMargin);
        make.width.height.offset(30);
        make.centerY.offset(0);
    }];
    
    UILabel *nicknameLabel = [UILabel lableWithSuperView:self.navigationBar.contentView font:UIFontMediumMake(12) color:UIColor.tj_333333Color title:HJUserInfo.nickname textAlignment:NSTextAlignmentLeft];
    [nicknameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.equalTo(avatarImageView.mas_right).offset(6);
    }];
    
    HJBarButton *moreButton = [HJBarButton barButtonWithImage:[UIImage imageNamed:@"more"] target:self action:@selector(didClickMoreButton)];
    HJBarButton *friendButton = [HJBarButton barButtonWithImage:[UIImage imageNamed:@"friend"] target:self action:@selector(didClickFriendButton)];
    moreButton.tj_size = CGSizeMake(32, 32);
    friendButton.tj_size = CGSizeMake(32, 32);
    self.navigationBar.rightBarButtons = @[friendButton, moreButton];
    
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 60)];
    headerView.backgroundColor = UIColor.whiteColor;
    
    UIView *searchView = [UIView addToView:headerView];
    searchView.backgroundColor = UIColor.tj_F6F6F6Color;
    searchView.addCornerRadius(10);
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(10);
        make.height.offset(40);
    }];
    
    UIImageView *searchIcon = [UIImageView addToView:searchView];
    searchIcon.image = [UIImage imageNamed:@"search_icon"];
    [searchIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(15);
    }];
    
    
    QMUITextField *textField = [QMUITextField addToView:searchView];
    textField.placeholder = @"search";
    textField.maximumTextLength = 20;
    textField.font = UIFontMake(14);
    textField.returnKeyType = UIReturnKeySearch;
    textField.delegate = self;
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.equalTo(searchIcon.mas_right).offset(10);
        make.right.offset(0);
        make.height.offset(40);
    }];
    
    self.tableView.tableHeaderView = headerView;
    self.view.backgroundColor = UIColor.tj_backgroundColor;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.tableView registerClass:HJConversationCell.class forCellReuseIdentifier:@"HJConversationCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 70;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight);
        make.left.right.bottom.offset(0);
    }];
    
    self.systemMessagesCount = 0;
    
    [HJVersionUpdate checkVersionUpdateInController:[HJTools currentViewController]];
    [HJMinePresent loadUserInfoComplete:nil];
    
    [self registeredNotification];
    [HJWebSocketManager.shareManager connect];
    
    [self loadConversationDataCompletion:nil];
}



- (void)registeredNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdateConversationInfoNotification:) name:updateConversationInfoNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleClearUnReadMessageNotification:) name:clearUnReadMessageNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdateOrAddConversationNotification:) name:updateConversationNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleWebSocketConnectStateChangeNotification:) name:webSocketConnectStateChangeNotification object:nil];
}


- (void)textFieldDidChange:(QMUITextField *)textField {
    
    _keyword = textField.text;
    UITextRange *textRange = textField.markedTextRange;
    if (textRange) return;
    
    if (isEmptyString(_keyword)) {
        for (HJChatSessionModel *obj in self.originalDatas) {
            obj.sessionNameAttributedstring = nil;
        }
        [self.datas removeAllObjects];
        [self.datas addObjectsFromArray:self.originalDatas];
        [self sortedDatas];
        [self.tableView reloadData];
        return;
    }
    
    [self.datas removeAllObjects];
    for (HJChatSessionModel *obj in self.originalDatas) {
        NSRange range = [obj.sessionName rangeOfString:self.keyword options:NSCaseInsensitiveSearch];
        if (range.location != NSNotFound) {
            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:obj.sessionName];
            [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.tj_mainColor range:range];
            obj.sessionNameAttributedstring = attrStr;
            [self.datas addObject:obj];
        } else {
            obj.sessionNameAttributedstring = nil;
        }
    }
    
    [self sortedDatas];
    [self.tableView reloadData];
}

- (void)didClickMoreButton {
    
    HJPopMenuController *popMenuController = [[HJPopMenuController alloc] initWithTypes:@[
        @(HJPopMenuTypeAddFriend),
        @(HJPopMenuTypeCreateGroup),
    ]];
    TJWeakify(self)
    popMenuController.controllerName = NSStringFromClass(self.class);
    [popMenuController showInController:self];
    [popMenuController setDidSelectItemBlock:^(HJPopMenuType type) {
        if (type == HJPopMenuTypeAddFriend) {
            HJNavigationController *navController = [[HJNavigationController alloc] initWithRootViewController:[[HJAddFriendController alloc] init]];
            [weakself presentViewController:navController animated:YES completion:nil];
            return;
        }
        
        if (type == HJPopMenuTypeCreateGroup) {
            HJNavigationController *navController = [[HJNavigationController alloc] initWithRootViewController:[[HJSelectFridendsController alloc] init]];
            [weakself presentViewController:navController animated:YES completion:nil];
            return;
        }
    }];
    
}


- (void)tapAvatarImageView {
    HJPersonalCenterController *personalCenterController = [[HJPersonalCenterController alloc] init];
    [self presentViewController:personalCenterController animated:NO completion:nil];
}


- (void)didClickFriendButton {
    [self.navigationController pushViewControllerWithName:@"HJFriendListController"];
}

- (BOOL)hiddenBackgroundView {
    return YES;
}

- (void)handleUpdateConversationInfoNotification:(NSNotification *)not {
    [self handleUpdateConversationInfo:not.object];
}

- (void)handleWebSocketConnectStateChangeNotification:(NSNotification *)not {
    HJWebSocketConnectState state = [not.object integerValue];
    if (state == HJWebSocketConnectStateConnecting) {
        
    } else if (state == HJWebSocketConnectStateSucceed) {
        
    }
}

- (void)reloadUnReadCount {
    NSInteger totalCount = 0;
    for (HJChatSessionModel *sessionModel in self.datas) {
        totalCount += sessionModel.unReadCount.integerValue;
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:messageBadgeChangeNotification object:@(totalCount)];
}

- (void)sortedDatas {
    NSMutableArray *topArray = [NSMutableArray array];
    NSMutableArray *messageArray = [NSMutableArray array];
    
    for (HJChatSessionModel *model in self.datas) {
        if (model.isTop.boolValue) {
            [topArray addObject:model];
        } else {
            [messageArray addObject:model];
        }
    }
    
    [self.datas removeAllObjects];
    
    
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:NO];
    if (topArray.count) {
        [topArray sortUsingDescriptors:@[sortDescriptor]];
        [self.datas addObjectsFromArray:topArray];
    }
    [messageArray sortUsingDescriptors:@[sortDescriptor]];
    [self.datas addObjectsFromArray:messageArray];
    
}

- (BOOL)replaceListModeltWithSessionModel:(HJChatSessionModel *)obj {
    
    HJChatSessionModel *targetMdoel = nil;
    for (HJChatSessionModel *sessionModel in self.datas) {
        if ([sessionModel.sessionId isEqualToString:obj.sessionId]) {
            targetMdoel = sessionModel;
            break;
        }
    }
    
    if (targetMdoel) {
        obj.isTop = targetMdoel.isTop;
        obj.isMute = targetMdoel.isMute;
        NSInteger index = [self.datas indexOfObject:targetMdoel];
        [self.datas replaceObjectAtIndex:index withObject:obj];
        return YES;
    } else {
        return NO;
    }
}

- (void)handleUpdateOrAddConversationNotification:(NSNotification *)not {
    
    HJChatSessionModel *obj = not.object;
    if (!obj) {
        [self loadConversationDataCompletion:nil];
        return;
    }
    
    if ([obj isKindOfClass:NSArray.class]) {
        
        
    }
    
    [obj bg_saveOrUpdateAsync:^(BOOL isSuccess) {
        if (![self replaceListModeltWithSessionModel:obj]) {
            [self.datas addObject:obj];
        }
        
        [self sortedDatas];
        dispatch_async_main_queue(^{
            [self reloadUnReadCount];
            [self.tableView reloadData];
        });
    }];
}

//会话的信息全部在更新之前查找好, 会话这里只是用来更新的, 不会进行排序和计算角标, 只是更新内容
- (void)handleUpdateConversationInfo:(HJChatSessionModel *)sessionModel {
    
    if (!sessionModel) return;
    
    if ([self replaceListModeltWithSessionModel:sessionModel]) {
        dispatch_async_main_queue(^{
            for (HJConversationCell *cell in self.tableView.visibleCells) {
                if ([cell.model.sessionId isEqualToString:sessionModel.sessionId]) {
                    cell.model = sessionModel;
                    break;
                }
            }
        });
    }
    
}

- (void)handleClearUnReadMessageNotification:(NSNotification *)not {
    NSString *sessionId = not.object;
    [HJIM.shareIM.conversationManager getConversationBySessionId:sessionId completion:^(HJChatSessionModel * _Nonnull sessionModel) {
        sessionModel.unReadCount = @"0";
        if (sessionModel.isMute.boolValue) {
            sessionModel.muteMessageUnReadCount = @"0";
        }
        [sessionModel bg_saveOrUpdate];
        [HJIM.shareIM.conversationManager updateBadge];
        [self handleUpdateConversationInfo:sessionModel];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJChatSessionModel *model = self.datas[indexPath.row];
    HJConversationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJConversationCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (_popMenuController) {
        return;
    }
    HJConversationCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    HJChatController *chatController = [HJChatController chatControllerWithSessionModel:cell.model];
    [self.navigationController pushViewController:chatController];
    [self readMessageWithSessionModel:cell.model indexPath:indexPath];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        TJWeakify(self)
        [weakself deleteConversationWithIndexPath:indexPath];
    }];
    
    deleteAction.backgroundColor = [UIColor redColor];
    return @[deleteAction];
}

- (void)tableViewCellLongPressGesture:(HJConversationCell *)cell {
    HJChatSessionModel *model = cell.model;
    HJPopMenuController *popMenuController = [[HJPopMenuController alloc] initWithTypes:@[
        @(model.isTop.boolValue ? HJPopMenuTypeCancelTop : HJPopMenuTypeTop),
        @(model.isMute.boolValue ? HJPopMenuTypeUnmute : HJPopMenuTypeMute),
        @(HJPopMenuTypeDelete)]
    ];
    _popMenuController = popMenuController;
    TJWeakify(self)
    popMenuController.sourceRect = [cell.superview convertRect:cell.frame toView:self.view];
    [popMenuController showInController:self];
    [popMenuController setDidSelectItemBlock:^(HJPopMenuType type) {
        
        if (type == HJPopMenuTypeTop || type == HJPopMenuTypeCancelTop) {
            BOOL isTop = HJPopMenuTypeTop == type;
            [HJIM.shareIM.conversationManager topWithSessionId:model.sessionId isTop:isTop isGroup:model.chatType == HJChatTypeGroup complete:^(NSError * _Nonnull error) {
                if (!error) {
                    model.isTop = toString(@(isTop));
                    [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
                        [weakself sortedDatas];
                        dispatch_async_main_queue(^{
                            [weakself.tableView reloadData];
                        });
                    }];
                }
            }];
            return;
        }
        
        if (type == HJPopMenuTypeMute || type == HJPopMenuTypeUnmute) {
            BOOL isMute = type == HJPopMenuTypeMute;
            [HJIM.shareIM.userManager muteWithSessionId:model.sessionId isMute:isMute isGroup:model.chatType == HJChatTypeGroup complete:^(NSError * _Nonnull error) {
                model.isMute = toString(@(isMute));
                [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
                    dispatch_async_main_queue(^{
                        cell.model = model;
                    });
                }];
            }];
            return;
        }
        
        if (type == HJPopMenuTypeDelete) {
            [weakself deleteConversationWithIndexPath:[self.tableView indexPathForCell:cell]];
            return;
        }
        
    }];
    
}

- (void)readMessageWithSessionModel:(HJChatSessionModel *)sessionModel indexPath:(NSIndexPath *)indexPath {
    
    if (sessionModel.isMute.boolValue) {
        sessionModel.muteMessageUnReadCount = @"0";
        [sessionModel bg_saveOrUpdate];
        HJConversationCell *cell = (HJConversationCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        cell.model = cell.model;
        return;
    }
    
    if (sessionModel.unReadCount.intValue > 0) {
        
        [HJIM.shareIM.userManager readMessageWithType:sessionModel.chatType sessionId:sessionModel.sessionId msgIds:nil begin:^{
            
            sessionModel.unReadCount = @"0";
            [sessionModel bg_saveOrUpdate];
            
            dispatch_async_main_queue(^{
                HJConversationCell *cell = (HJConversationCell *)[self.tableView cellForRowAtIndexPath:indexPath];
                cell.model.unReadCount = @"0";
                cell.model = cell.model;
                [HJIM.shareIM.conversationManager updateBadge];
            });
            
        } completion:^(NSError * _Nullable error) {
            if (!error) {//
                NSLog(@"已读消息成功");
            }
        }];
    }
}


- (void)deleteConversationWithIndexPath:(NSIndexPath *)indexPath {
    
    HJChatSessionModel *model = self.datas[indexPath.row];
    [HJAlertController alertInController:self title:nil message:@"确定要删除会话消息吗？" left:^(HJAlertAction * _Nonnull action) {
        action.title = @"删除";
        action.titleColor = UIColor.tj_redColor;
        [action setHandler:^{
            [HJIM.shareIM.conversationManager deleteConversationWithSessionId:model.sessionId completion:^(NSError * _Nonnull error) {
                [self.datas removeObject:model];
                [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }];
        }];
    } right:^(HJAlertAction * _Nonnull action) {
        action.title = @"取消";
        action.titleColor = UIColor.tj_101320Color;
    }];
    
}

//群信息只有点击进去,或者第一次发送的时候才会改变, 和个人的时候差不多, 还有拉取离线消息的时候更新发送者信心和群信息

- (void)updateSessionInfo {
    for (HJChatSessionModel *sessionModel in self.datas) {
        
        if (isEmptyString(sessionModel.sessionAvatar) || isEmptyString(sessionModel.sessionName)) {
            
            NSString *queryUserId = TJIM_isSelf(sessionModel.senderId) ? sessionModel.receiveId : sessionModel.senderId;
            
            [[HJIM shareIM].userManager loadUserInfoWithUserId:queryUserId complete:^(HJChatUserModel * _Nullable userModel) {
                if (userModel) {
                    sessionModel.sessionAvatar = userModel.avatar;
                    sessionModel.sessionName = userModel.showName;
                    [sessionModel bg_saveOrUpdate];
                    [self handleUpdateConversationInfo:sessionModel];
                }
            }];
        }
    }
    
}

- (void)loadConversationDataCompletion:(void (^__nullable)(void))completion {
    [[HJIM shareIM].conversationManager allConversationListCompletion:^(NSArray * _Nonnull list) {
                
//        NSLog(@"list = %@", list);
        
        self.originalDatas = [NSArray arrayWithArray:list];
        
        [self.datas removeAllObjects];
        if (list.count) {
            [self.datas addObjectsFromArray:list];
        }
        [self sortedDatas];
        dispatch_async_main_queue(^{
            [self.tableView reloadData];
        });
        
        if (completion) {
            completion();
        }
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [HJWebSocketManager.shareManager tryConnect];
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
